from urllib import request
import json
import companylist


def autoComNum(number):
    url = "https://www.kuaidi100.com/autonumber/autoComNum?text=%s" % number
    req = request.urlopen(url)
    res = json.load(req).get("auto")
    return [i.get("comCode") for i in res]


def getQuery(number, com):
    req = request.urlopen(
        "https://www.kuaidi100.com/query?type=%s&postid=%s" % (com,number))
    res = json.load(req)
    return res


def printResult(msg):
    if(msg["message"] != "ok"):
        print("查询失败")
    print("【%s】(%s) 的跟踪信息如下" %
          (companylist.companies.get(msg["com"]), msg["nu"]))
    for item in msg["data"]:
        print("[%s]%s" % (item["time"], item["context"]))


number = "443786388324"
company = autoComNum(number)
msgs = list(map(lambda c:getQuery(number,c),company))
for msg in msgs:
    printResult(msg)